package com.bosssoft.hr.train.jsp.example.controller;

import com.alibaba.fastjson.JSON;
import com.bosssoft.hr.train.jsp.example.pojo.User;
import com.bosssoft.hr.train.jsp.example.service.impl.UserServiceImpl;
import com.bosssoft.hr.train.jsp.example.service.UserService;
import com.bosssoft.hr.train.jsp.example.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @description: 用户列表查询Controller 将数据库读取的数据经过json处理响应请求
 * @author: ChenTong
 * @create: 2020-05-30 11:22
 * @since
 **/
@Slf4j
public class QueryUserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String usersJson = this.listAllUsers();
        log.info(usersJson);

        try {
            JSONUtil.writeJson(resp,JSON.parseObject(usersJson));
        }catch (IOException  e){
            log.error(e.getMessage(),e);
        }



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // DO NOTHING
    }

    private String listAllUsers(){
        UserService userService = new UserServiceImpl();
        try {
            List<User> userList = userService.listAllUser();
            return JSON.toJSONString(userList);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return "";

    }

}
